<template>
  <el-dialog
    :visible.sync="visible"
    :before-close="beforeClose"
    :close-on-click-modal="false"
    append-to-body
    title="抵质押登记表"
    width="1100px"
    top="30px"
  >
    <table
      class="table table-bordered text-center table-sm table-vertical-middle"
      v-loading="loading"
    >
      <colgroup>
        <col width="4%" />
        <col width="9%" />
        <col width="12%" />
        <col width="13%" />
        <col width="13%" />
        <col width="9%" />
        <col width="8%" />
        <col width="12%" />
        <col width="7%" />
        <col width="14%" v-if="!isApprove" />
        <col width="7%" v-if="isApprove" />
        <col width="7%" v-if="isApprove" />
      </colgroup>
      <thead>
        <tr>
          <th>序号</th>
          <th>抵质押物类型</th>
          <th>抵质押物名称</th>
          <th>抵质押编号</th>
          <th>抵押登记时间</th>
          <th>评估价格(元)</th>
          <th>提交人</th>
          <th>备注</th>
          <th>附件</th>
          <th>{{ viewMode ? '审核状态' : '操作' }}</th>
          <th v-if="isApprove">操作</th>
        </tr>
      </thead>
      <tr v-if="!viewMode">
        <td>-</td>
        <td class="input-td">
          <c-select
            v-model="editData.guaranty_type"
            placeholder="类型"
            :options="enumPledgeType"
          ></c-select>
        </td>
        <td class="input-td">
          <el-input
            v-model="editData.guaranty_name"
            autosize
            type="textarea"
            placeholder="名称"
          ></el-input>
        </td>
        <td class="input-td">
          <el-input
            v-model="editData.guaranty_no"
            autosize
            type="textarea"
            placeholder="编号"
          ></el-input>
        </td>
        <td class="input-td">
          <el-date-picker
            class="w-100"
            v-model="editData.guaranty_date"
            type="date"
            placeholder="操作时间"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </td>
        <td class="input-td">
          <el-input
            v-model="editData.guaranty_value"
            v-input-number="{ min: 0, fixed: 2 }"
            placeholder="估价（元）"
          ></el-input>
        </td>
        <td>{{ realName }}</td>
        <td class="input-td">
          <el-input
            v-model="editData.remark"
            autosize
            type="textarea"
            placeholder="备注"
          ></el-input>
        </td>
        <td>
          <el-button size="small" :disabled="disabled" @click="handleAttach">上传</el-button>
        </td>
        <td>
          <el-button size="small" :loading="buttonLoading" :disabled="disabled" @click="submit">
            添加
          </el-button>
        </td>
      </tr>
      <tr v-if="!tableData.length">
        <td :colspan="isApprove ? 11 : 10">-</td>
      </tr>
      <tr v-for="(p, index) of tableData" :key="index">
        <td>{{ index + 1 }}</td>
        <td>{{ enumPledgeType[p.guaranty_type] }}</td>
        <td>{{ p.guaranty_name }}</td>
        <td>{{ p.guaranty_no }}</td>
        <td>{{ p.guarantyDate }}</td>
        <td>{{ p.guaranty_value }}</td>
        <td>{{ p.submit_person_name }}</td>
        <td>{{ p.remark }}</td>
        <td>
          <span v-if="!p.attachment">无</span>
          <el-button v-else size="small" @click="handleAttachView(p)">查看</el-button>
        </td>
        <td>
          <span v-if="!viewMode">
            <el-button type="text" @click="handleEdit(p)" class="m-0 p-0">修改</el-button>
            <el-button class="text-danger mx-1 p-0" type="text" @click="handleDelete(p)">
              删除
            </el-button>
            <el-button type="text" @click="handleView(p)" class="m-0 p-0">查看</el-button>
          </span>
          <span
            v-else
            class="badge"
            :class="`badge-${enumPledgeDetailStyle[p.item_guaranty_status]}`"
          >
            {{ enumPledgeDetailStatus[p.item_guaranty_status] }}
          </span>
        </td>
        <td v-if="isApprove">
          <el-button type="text" @click="handleApprove(p)">审核</el-button>
        </td>
      </tr>
    </table>

    <div class="text-center" v-if="!viewMode && tableData.length">
      <el-button type="primary" class="btn-long" :loading="buttonLoading" @click="handleSubmit">
        提交审核
      </el-button>
      <el-button class="btn-long" @click="beforeClose">取消</el-button>
    </div>

    <div class="text-center" v-if="isApprove">
      <el-button type="primary" class="btn-long" :loading="buttonLoading" @click="handleApproveAll">
        完成审核
      </el-button>
      <el-button type="danger" class="btn-long" :loading="buttonLoading" @click="handleBack">
        退回
      </el-button>
      <el-button class="btn-long" @click="beforeClose">取消</el-button>
    </div>

    <register-table-detail-dialog
      :visible.sync="detailVisible"
      :view-mode="detailViewMode"
      :is-approve="detailApprove"
      @success="handleSuccess"
      :table-data="tableData"
      :form-data="detailData"
      :query-id="queryId"
    ></register-table-detail-dialog>

    <attachment-dialog
      :visible.sync="attachVisible"
      ref="attach"
      @save="saveData"
      :query-id="queryId"
    ></attachment-dialog>

    <attachment-view :visible.sync="itemAttachVisible" :attach="attach"></attachment-view>
  </el-dialog>
</template>

<script>
import {
  enumPledgeType,
  enumPledgeDetailStatus,
  enumPledgeDetailStyle,
} from '@/credit/views/city/risk/pledge/enum'
import { mapGetters } from 'vuex'
import RegisterTableDetailDialog from '@/credit/views/city/risk/pledge/RegisterTableDetailDialog'
import AttachmentDialog from '@/credit/views/city/risk/pledge/Attachment'
import AttachmentView from '@/credit/views/city/risk/pledge/AttachmentView'
import { add, dateFormat, arrayFromString } from '@vimi/utils-tool'
import { deleteOss } from '@/common/api/oss'
import { addHistory } from '@/credit/views/city/archives/historyMixins'
export default {
  components: {
    RegisterTableDetailDialog,
    AttachmentDialog,
    AttachmentView,
  },
  props: {
    queryId: String,
    registerId: { type: String, default: '' },
    visible: Boolean,
    viewMode: {
      type: Boolean,
      default: true,
    },
    isApprove: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      enumPledgeDetailStatus,
      enumPledgeDetailStyle,
      enumPledgeType,
      loading: false,
      tableData: [],
      editData: {},
      detailVisible: false,
      attachVisible: false,
      buttonLoading: false,
      params: {},
      tableName: 'guaranty_register_detail',
      masterTableName: 'guaranty_register',
      disabled: false,
      itemAttachVisible: false,
      attach: '',
      detailData: {},
      detailViewMode: false,
      detailApprove: false,
    }
  },
  computed: {
    ...mapGetters(['user']),
    realName() {
      return this.user.realName
    },
  },
  watch: {
    registerId() {
      this.params['guaranty_register_id.eq'] = this.registerId
      this.getData()
    },
  },
  created() {},
  methods: {
    handleSuccess() {
      this.getData()
      this.$emit('success', true)
    },
    updateData(data) {
      if (!this.registerId) {
        return Promise.reject(new Error(''))
      }
      return this.$api.updateData(this.$serviceName, this.masterTableName, this.registerId, data)
    },
    handleApproveAll() {
      const data = {
        register_status: 3,
        register_approval_time: dateFormat(new Date()),
      }
      this.buttonLoading = true
      this.updateData(data)
        .then(() => {
          this.$emit('success', true)
          this.$message.success('审核成功')
          this.$emit('next', true)
          this.beforeClose()
        })
        .catch(() => {
          this.$message.error('审核失败!')
        })
        .finally(() => {
          this.buttonLoading = false
        })
    },
    handleBack() {
      const data = {
        register_status: 0,
        register_approval_time: dateFormat(new Date()),
      }
      this.buttonLoading = true
      this.updateData(data)
        .then(() => {
          this.$emit('success', true)
          this.$message.success('已退回')
          this.beforeClose()
        })
        .catch(() => {
          this.$message.error('退回失败!')
        })
        .finally(() => {
          this.buttonLoading = false
        })
    },
    handleApprove(p) {
      this.detailData = { ...p }
      this.detailViewMode = true
      this.detailVisible = true
      this.detailApprove = true
    },
    handleSubmit() {
      const masterData = {
        register_status: 1,
        customer_related_id: this.queryId,
        register_time: dateFormat(new Date()),
      }
      if (this.registerId) {
        masterData.guaranty_register_id = this.registerId
      }
      const dataArray = this.tableData.map(item => {
        return {
          id: item.id,
          guaranty_register_id: item.guaranty_register_id,
          item_guaranty_status: 1,
        }
      })
      const formData = {
        masterTableInfo: JSON.stringify(masterData),
        masterTableName: this.masterTableName,
        slaveTableInfo: JSON.stringify(dataArray),
        slaveTableName: this.tableName,
      }
      this.buttonLoading = true
      if (this.registerId) {
        this.putData(formData).then(() => {
          this.beforeClose()
        })
      } else {
        this.addItemData(formData).then(() => {
          this.beforeClose()
        })
      }
    },
    handleDelete(p) {
      this.$utils
        .msgbox({
          message: `确定删除?`,
          type: 'warning',
          beforeClose: () => this.$api.deleteData(this.$serviceName, this.tableName, p.id),
        })
        .then(() => {
          this.addHistoryRecord(this.registerId, p, 3)
          this.updateData({
            guaranty_value_total: this.getValueTotal(p.id),
            register_count: this.tableData.length - 1,
          }).then(() => {
            this.$emit('success', true)
          })
          if (p.attachment) {
            deleteOss(arrayFromString(p.attachment))
          }
          this.$message.success('删除成功！')
          this.getData()
        })
        .catch(() => this.$message.error(`删除失败，请重试！`))
    },
    handleAttachView(row) {
      this.itemAttachVisible = true
      this.attach = row.attachment || ''
    },
    getData() {
      if (!this.registerId) {
        this.tableData = []
        return
      }
      this.disabled = false
      this.loading = true
      this.$api
        .getData(this.$serviceName, this.tableName, this.params, { create_time: 'desc' })
        .then(res => {
          const data = res?.data ?? []
          this.tableData = data.map(this.dataAdapter)
        })
        .catch(() => {
          this.disabled = true
        })
        .finally(() => {
          this.loading = false
        })
    },
    dataAdapter(item) {
      item.guarantyDate = dateFormat(item.guaranty_date, 'yyyy年MM月dd日')
      return item
    },
    submit() {
      if (!this.editData.guaranty_type) {
        return this.$message.warning('请选择抵质押物类型')
      }
      if (!this.editData.guaranty_name) {
        return this.$message.warning('请输入抵质押物名称')
      }
      this.buttonLoading = true
      this.$refs.attach.submit()
    },
    init() {
      this.editData = {}
      this.$refs.attach.clearImages()
    },
    handleAttach() {
      this.attachVisible = true
    },
    handleView(p = {}) {
      this.detailData = { ...p }
      this.detailViewMode = true
      this.detailVisible = true
      this.detailApprove = false
    },
    handleEdit(p = {}) {
      this.detailData = { ...p }
      this.detailViewMode = false
      this.detailVisible = true
      this.detailApprove = false
    },
    beforeClose() {
      this.init()
      this.$emit('update:visible', false)
    },
    saveData(str) {
      const masterData = {
        customer_related_id: this.queryId,
        guaranty_value_total: this.getValueTotal(),
        register_count: this.tableData.length + 1,
      }
      const data = {
        attachment: str,
        guaranty_date: this.editData.guaranty_date,
        guaranty_name: this.editData.guaranty_name,
        guaranty_no: this.editData.guaranty_no,
        guaranty_type: this.editData.guaranty_type,
        guaranty_value: this.editData.guaranty_value,
        remark: this.editData.remark,
        submit_person_name: this.realName,
      }
      if (this.registerId) {
        masterData.guaranty_register_id = this.registerId
        data.guaranty_register_id = this.registerId
      }
      const dataArray = this.tableData.map(item => {
        return {
          id: item.id,
          guaranty_register_id: item.guaranty_register_id,
        }
      })
      dataArray.push(data)
      const formData = {
        masterTableInfo: JSON.stringify(masterData),
        masterTableName: this.masterTableName,
        slaveTableInfo: JSON.stringify(dataArray),
        slaveTableName: this.tableName,
      }
      if (this.registerId) {
        this.putData(formData).then(() => {
          this.addHistoryRecord(this.registerId, data)
        })
      } else {
        this.addItemData(formData).then(() => {
          this.$api
            .getData(this.$serviceName, this.masterTableName, {
              'customer_related_id.eq': this.queryId,
            })
            .then(res => {
              const master = res?.data?.[0] ?? {}
              this.addHistoryRecord(master.guaranty_register_id, data)
            })
        })
      }
    },
    // 添加操作记录
    addHistoryRecord(archiveId, data, type = 2) {
      if (!archiveId) {
        return
      }
      const getRecordItem = (key, label, newVal, oldVal, type) => ({
        update_record_field: key,
        update_record_field_name: label,
        update_record_id: archiveId,
        update_record_value_aft: newVal,
        update_record_value_bef: oldVal,
        update_type: type,
      })

      const masterData = {
        record_id: archiveId,
        submit_person: this.userId,
        submit_person_name: this.user.realName,
      }

      // 改变的数据
      const slaveData = []
      // 新增 2 删除 3
      slaveData.push(
        getRecordItem(
          'guaranty_type',
          `${enumPledgeType[data.guaranty_type]}物`,
          data.guaranty_name,
          '',
          type
        )
      )
      return addHistory(masterData, slaveData)
    },
    getValueTotal(id = '') {
      let sum = 0
      this.tableData.forEach(item => {
        if (id !== item.id) {
          sum = add(sum, item.guaranty_value)
        }
      })
      sum = add(sum, this.editData.guaranty_value)
      return sum
    },
    addItemData(formData) {
      return this.$api
        .relatedBatch(this.$serviceName, formData)
        .then(() => {
          this.getData()
          this.$emit('success', true)
          this.init()
          this.$message.success('登记成功')
        })
        .catch(() => {
          this.$message.error('登记失败，请重试！')
        })
        .finally(() => {
          this.buttonLoading = false
        })
    },
    putData(formData) {
      return this.$api
        .relatedUpdate(this.$serviceName, formData)
        .then(() => {
          this.$emit('success', true)
          this.getData()
          this.init()
          this.$message.success('登记成功')
        })
        .catch(() => {
          this.$message.error('登记失败，请重试！')
        })
        .finally(() => {
          this.buttonLoading = false
        })
    },
  },
}
</script>
<style lang="scss" scoped>
.input-td {
  background: #ffffee;
}
</style>
